package com.industry.system.satoken;

import cn.dev33.satoken.stp.StpInterface;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.industry.framework.common.constant.Global;
import com.industry.framework.common.redis.RedisUtils;
import com.industry.system.dal.db.AuthBizMapper;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author jsy
 * @description:自定义权限加载接口实现类
 * @date 2025/1/7 16:35
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    /**
     * @description: 返回一个账号所拥有的权限码集合
     * @author: jsy
     * @time: 2025/1/7 16:35
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth((Long) loginId, Global.authPermissionPrefix);
    }

    /**
     * @description: 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     * @author: jsy
     * @time: 2025/1/7 16:36
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth((Long) loginId, Global.authRolePrefix);
    }

    /**
     * @description: 获取权限或角色
     * @author: jsy
     * @time: 2025/1/8 15:56
     */
    public List<String> getAuth(Long loginId, String prefix) {
        //TODO 暂时这么些，后期需要改一下
        String key = prefix + ":" + loginId;
        String authValue = RedisUtils.getCacheObject(key);
        if (StringUtils.isBlank(authValue)) {
            return Collections.emptyList();
        }
        List<String> roleOrAuthList = new LinkedList<>();
        roleOrAuthList = new Gson().fromJson(authValue, new TypeToken<List<String>>() {
        }.getType());
        return roleOrAuthList;
    }

}

